import React, {Component} from 'react';

// 引入store,用于获取redux中保存的状态
import store from "../../redux/store";

// 引入count_action_creators 文件，专门用于创建action对象
import {createDecrementAction, createIncrementAction} from "../../redux/count_action_creators"


class Count extends Component {

  increment = () => {
    // 点击加执行的事件
    const {value} = this.selectedNumber;
    // 通知redux加 value
    store.dispatch(createIncrementAction(value * 1))
  }

  decrement = () => {
    // 点击减触发的事件
    const {value} = this.selectedNumber;
    store.dispatch(createDecrementAction(value * 1))
  }

  incrementIfOdd = () => {
    // 当前和为奇数时再加
    if (store.getState() % 2 !== 0) {
      const {value} = this.selectedNumber;
      store.dispatch(createIncrementAction(value * 1))
    }
  }

  timeOutMethod = (fn, wait = 500) => {
    let timeout;
    return function (event) {
      clearTimeout(timeout);  // 每次触发时先清除上一次的定时器,然后重新计时
      timeout = setTimeout(() => {
        fn(event)
      }, wait);
    }
  }


  incrementIfAsync = () => {
    // 异步加法

    this.timeOutMethod(() => {
      const {value} = this.selectedNumber;
      // 通知redux加 value
     store.dispatch(createIncrementAction(value * 1))
    })();
  }

  render() {
    return (
      <div>
        <h1>当前求和为{store.getState()}</h1>
        <select ref={c => this.selectedNumber = c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>
        &nbsp;
        <button onClick={this.increment}>加</button>
        &nbsp;
        <button onClick={this.decrement}>减</button>
        &nbsp;
        <button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>
        &nbsp;
        <button onClick={this.incrementIfAsync}>异步加</button>
      </div>
    );
  }
}

export default Count;